﻿/*
 * Copyright 2014 Francois Karman
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

using Quartz.WebManager.Logic;
using Quartz.WebManager.Model;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace Quartz.WebManager.Web.ApiControllers
{
    /// <summary>
    /// Displays the data about the running schedulers.
    /// </summary>
    [RoutePrefix("api/schedulers")]
    public class SchedulersController : ApiController
    {
        /// <summary>
        /// Lists all the existing schedulers.
        /// </summary>
        /// <returns>All the existing schedulers.</returns>
        [Route("")]
        [HttpGet]
        public IEnumerable<SchedulerInstance> ListAll()
        {
            return DataAccess.Instance.RetrieveSchedulerStates();
        }

        /// <summary>
        /// Counts all the existing schedulers by state.
        /// </summary>
        /// <returns>The count of scheulders on each state.</returns>
        [Route("by-states")]
        [HttpGet]
        public IDictionary<string, int> ByStates()
        {
            return DataAccess.Instance.RetrieveSchedulerStates()
                .GroupBy(s => s.State)
                .ToDictionary(g => g.Key, g => g.Count());
        }

        /// <summary>
        /// Lists all the errors that occurs during scheduled jobs.
        /// </summary>
        /// <param name="offset">The starting offset - for pagination.</param>
        /// <param name="limit">The maximum number of element to return - for pagination.:</param>
        /// <returns>The errors that occurs during scheduled jobs.</returns>
        [Route("errors")]
        [HttpGet]
        public IEnumerable<SchedulerError> ListErrors(int offset, int limit)
        {
            return DataAccess.Instance.RetrieveSchedulerErrors(offset, limit);
        }
    }
}
